package pc.nick.http;

import java.io.*;
import java.util.Date;

public class HttpServletResponse {

    private HttpServletRequest request;

    // 将当前工作项目路径拼接一个“/”,再拼接一个“static”：得到一个完整的文件路径，即：项目路径/static
    private String webRoot = System.getProperty("user.dir") + File.separator + "static";

    private OutputStream oos;

    public HttpServletResponse(HttpServletRequest request, OutputStream oos) {
        this.request = request;
        this.oos = oos;
    }



    public void sendRedirect() {
        int code = 200;
        // 1.取出request中uri
        String uri = request.getRequestURI();
        File file;
        String fileName;
        if(uri.endsWith("/")){ // 如果以“/”结尾的，就会在后面加一个index.html
            fileName = uri + "index.html";
        }else{
            fileName = uri;
        }
        file = new File(webRoot, fileName);

        // 2.判断文件是否存在
        if(!file.exists()){
            file = new File(webRoot, "404.html");
            code = 404;
        }

        // 发送响应，不同的文件返回不同类型
        if(file.getName().endsWith(".jpg")){
            send(file, "application/x-jpg", code);
        }else if(file.getName().endsWith(".jpe") || file.getName().endsWith(".jpeg")){
            send(file, "image/jpeg", code);
        }else if(file.getName().endsWith(".gif")){
            send(file, "image/gif", code);
        }else if(file.getName().endsWith(".js")){
            send(file, "application/x-javascript", code);
        }else if(file.getName().endsWith(".swf")){
            send(file, "application/x-shockwave-flash", code);
        }else{
            send(file, "text/html", code);
        }

    }

    // 返回给前端响应流
    private void send(File file, String contentType, int code) {
        try {
            String reponseHeader = genProtocol(file.length(), contentType, code);
            byte[] bs = readFile(file);
            this.oos.write(reponseHeader.getBytes());
            this.oos.flush();
            this.oos.write(bs);
            this.oos.flush();
        } catch (IOException e) {
           e.printStackTrace();
        }finally {
            try {
                this.oos.close();
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }

    // 读取文件
    private byte[] readFile(File file) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FileInputStream fis = null;

        try {
            fis = new FileInputStream(file);
            byte[] bs = new byte[1024];
            int length;
            while((length = fis.read(bs, 0, bs.length)) != -1){
                baos.write(bs, 0, length);
                baos.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if(fis != null){
                    fis.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
       return baos.toByteArray();
    }

    // 拼接响应协议
    private String genProtocol(long length, String contentType, int code) {
        String result = "HTTP/1.1 " + code + " OK\r\n";
        result += "Server: myTomcat\r\n";
        result += "Content-Type: " + contentType + ";charset=utf-8\r\n";
        result += "Content-Length: " + length + "\r\n";
        result += "Date: " + new Date() + "\r\n";
        result += "\r\n";
        return result;
    }

    // 通过调用 getWriter()方法来获取一个用于输出字符串的PrintWriter对象。
    // 然后，你可以使用这个PrintWriter对象来将HTML内容、文本数据或其他字符数据写入到HTTP 响应中，
    // 最终发送给客户端浏览器。
    public PrintWriter getWriter() {
       return new PrintWriter(this.oos);
    }
}
